<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('账户余额报表')" />
    <th:block th:include="include :: bootstrap-select-css" />
</head>
<body class="gray-bg">
    <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <div class="select-list">
                    <ul>
                        <li class="select-time">
                            <label>统计时间： </label>
                            <input type="text" class="time-input" id="startTime" placeholder="开始时间" name="params[beginTime]"/>
                            <span>-</span>
                            <input type="text" class="time-input" id="endTime" placeholder="结束时间" name="params[endTime]"/>
                        </li>
                        <li>
                            <label>账户选择：</label>
                            <select id="accountSelect" name="accountId">
                                <option value="">所有账户</option>
                            </select>
                        </li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="searchData()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="resetForm()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                        </li>
                    </ul>
                </div>
            </div>
            
            <div class="col-sm-12 select-table">
                <div class="btn-group-sm" id="toolbar" role="group">
                    <a class="btn btn-success" onclick="exportExcel()" shiro:hasPermission="fin:report:export">
                        <i class="fa fa-download"></i> 导出
                    </a>
                </div>
                <!-- 账户余额表格 -->
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>账户余额统计</h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                            <a class="close-link">
                                <i class="fa fa-times"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <div class="table-responsive">
                            <table id="accountBalanceTable" class="table table-striped table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th>账户名称</th>
                                        <th>账号</th>
                                        <th>银行名称</th>
                                        <th>当前余额</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- 数据由JavaScript填充 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- 账户余额趋势图 -->
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>账户余额趋势图</h5>
                        <div class="ibox-tools">
                            <div class="btn-group" style="margin-right: 10px;">
                                <button type="button" class="btn btn-sm btn-default active" id="chartTypeLine">
                                    <i class="fa fa-line-chart"></i> 折线图
                                </button>
                                <button type="button" class="btn btn-sm btn-default" id="chartTypeArea">
                                    <i class="fa fa-area-chart"></i> 面积图
                                </button>
                            </div>
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                            <a class="close-link">
                                <i class="fa fa-times"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <div class="echarts" id="balanceTrendChart" style="height:500px;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: bootstrap-select-js" />
    <th:block th:include="include :: echarts-js" />
    
    <script type="text/javascript">
        var prefix = ctx + "fin/report";
        var balanceTrendChart;
        var currentChartType = 'line'; // 默认为折线图
        var accountBalanceData = []; // 存储账户余额数据
        var balanceTrendData = []; // 存储账户余额趋势数据
        
        $(function() {
            loadAccountBalanceData();
            loadBalanceTrendData();
            
            // 添加切换图表类型按钮点击事件
            $("#chartTypeLine").click(function() {
                $(this).addClass("active");
                $("#chartTypeArea").removeClass("active");
                currentChartType = 'line';
                updateBalanceTrendChart();
            });
            
            $("#chartTypeArea").click(function() {
                $(this).addClass("active");
                $("#chartTypeLine").removeClass("active");
                currentChartType = 'area';
                updateBalanceTrendChart();
            });
        });
        
        // 加载账户余额数据
        function loadAccountBalanceData() {
            $.ajax({
                type: "post",
                url: prefix + "/getAccountBalanceData",
                dataType: "json",
                success: function(data) {
                    if (data.code == 0) {
                        processAccountBalanceData(data.data);
                    } else {
                        $.modal.alertError(data.msg);
                    }
                }
            });
        }
        
        // 处理账户余额数据
        function processAccountBalanceData(data) {
            accountBalanceData = data;
            
            // 清空表格
            $("#accountBalanceTable tbody").empty();
            
            // 清空账户下拉框
            $("#accountSelect").empty();
            $("#accountSelect").append('<option value="">所有账户</option>');
            
            // 处理数据
            if (data && data.length > 0) {
                $.each(data, function(index, item) {
                    if (item) {
                        // 添加到表格
                        if (item.accountId != 0) { // 不显示总计行
                            var row = '<tr>' +
                                '<td>' + item.accountName + '</td>' +
                                '<td>' + (item.accountNo || '') + '</td>' +
                                '<td>' + (item.bankName || '') + '</td>' +
                                '<td class="text-right">' + formatMoney(item.balance) + '</td>' +
                                '</tr>';
                            $("#accountBalanceTable tbody").append(row);
                            
                            // 添加到账户下拉框
                            $("#accountSelect").append('<option value="' + item.accountId + '">' + item.accountName + '</option>');
                        } else {
                            // 总计行特殊样式
                            var totalRow = '<tr class="active">' +
                                '<td><strong>' + item.accountName + '</strong></td>' +
                                '<td></td>' +
                                '<td></td>' +
                                '<td class="text-right"><strong>' + formatMoney(item.balance) + '</strong></td>' +
                                '</tr>';
                            $("#accountBalanceTable tbody").append(totalRow);
                        }
                    }
                });
            } else {
                // 如果没有数据，显示提示信息
                $("#accountBalanceTable tbody").append('<tr><td colspan="4" class="text-center">暂无数据</td></tr>');
            }
            
            // 刷新下拉框组件
            $("#accountSelect").selectpicker('refresh');
        }
        
        // 加载余额趋势数据
        function loadBalanceTrendData() {
            var startTime = $("#startTime").val();
            var endTime = $("#endTime").val();
            var accountId = $("#accountSelect").val();
            
            $.ajax({
                type: "post",
                url: prefix + "/getAccountBalanceTrendData",
                data: {
                    startDate: startTime,
                    endDate: endTime,
                    accountId: accountId || ""
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == 0) {
                        processBalanceTrendData(data.data);
                    } else {
                        $.modal.alertError(data.msg);
                    }
                }
            });
        }
        
        // 处理余额趋势数据
        function processBalanceTrendData(data) {
            balanceTrendData = data;
            updateBalanceTrendChart();
        }
        
        // 更新余额趋势图表
        function updateBalanceTrendChart() {
            // 初始化ECharts实例（如果尚未初始化）
            if (!balanceTrendChart) {
                balanceTrendChart = echarts.init(document.getElementById('balanceTrendChart'));
                
                // 响应式图表
                window.addEventListener('resize', function() {
                    balanceTrendChart.resize();
                });
            }
            
            var option = getBalanceTrendChartOption();
            
            // 使用配置项和数据显示图表
            balanceTrendChart.setOption(option, true);
        }
        
        // 获取余额趋势图配置
        function getBalanceTrendChartOption() {
            // 按账户ID分组数据
            var accountGroups = {};
            var dateSet = new Set();
            
            balanceTrendData.forEach(function(item) {
                // 记录所有出现的日期
                dateSet.add(item.recordDate);
                
                // 按账户ID分组
                if (!accountGroups[item.accountId]) {
                    accountGroups[item.accountId] = {
                        name: item.accountName,
                        data: {}
                    };
                }
                
                // 保存每个日期的余额
                accountGroups[item.accountId].data[item.recordDate] = item.balance;
            });
            
            // 转换日期集合为排序的数组
            var dateList = Array.from(dateSet).sort();
            
            // 构建系列数据
            var series = [];
            var colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'];
            var colorIndex = 0;
            
            for (var accountId in accountGroups) {
                var accountData = accountGroups[accountId];
                var seriesData = [];
                
                // 对每个日期，获取该账户的余额
                dateList.forEach(function(date) {
                    seriesData.push(accountData.data[date] || 0);
                });
                
                // 创建系列
                var seriesItem = {
                    name: accountData.name,
                    type: currentChartType === 'line' ? 'line' : 'line', // 都是line，但area需要设置areaStyle
                    data: seriesData,
                    symbol: 'circle',
                    symbolSize: 6,
                    itemStyle: {
                        color: colors[colorIndex % colors.length]
                    },
                    lineStyle: {
                        width: 2
                    },
                    smooth: true
                };
                
                // 如果是面积图，添加区域样式
                if (currentChartType === 'area') {
                    seriesItem.areaStyle = {
                        opacity: 0.3
                    };
                }
                
                series.push(seriesItem);
                colorIndex++;
            }
            
            var option = {
                backgroundColor: '#fff',
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    },
                    formatter: function(params) {
                        var result = params[0].axisValue + '<br/>';
                        params.forEach(function(param) {
                            var color = param.color;
                            var value = formatMoney(param.value);
                            result += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:' + color + '"></span>';
                            result += param.seriesName + ': ' + value + '<br/>';
                        });
                        return result;
                    }
                },
                legend: {
                    data: Object.values(accountGroups).map(function(account) {
                        return account.name;
                    }),
                    top: 10,
                    right: '10%',
                    textStyle: {
                        fontSize: 12
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '10%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: dateList,
                    name: '日期',
                    nameLocation: 'middle',
                    nameGap: 40,
                    nameTextStyle: {
                        fontSize: 14,
                        fontWeight: 'bold',
                        padding: [15, 0, 0, 0],
                        color: '#333'
                    },
                    axisLabel: {
                        rotate: 45,
                        interval: Math.floor(dateList.length / 12), // 自动计算间隔以避免标签重叠
                        textStyle: {
                            fontSize: 12
                        }
                    },
                    boundaryGap: false
                },
                yAxis: {
                    type: 'value',
                    name: '余额(元)',
                    nameLocation: 'middle',
                    nameGap: 50,
                    nameTextStyle: {
                        fontSize: 14,
                        fontWeight: 'bold',
                        padding: [0, 0, 20, 0],
                        color: '#333'
                    },
                    axisLabel: {
                        formatter: function(value) {
                            return formatMoney(value, 0);
                        },
                        fontSize: 12
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: '#DDD'
                        }
                    }
                },
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },
                    {
                        start: 0,
                        end: 100
                    }
                ],
                series: series
            };
            
            return option;
        }
        
        // 格式化货币数字
        function formatMoney(value, decimals) {
            if (value === undefined || value === null) {
                return '0.00';
            }
            
            decimals = decimals !== undefined ? decimals : 2;
            value = parseFloat(value);
            return '¥' + value.toFixed(decimals).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        }
        
        // 搜索按钮点击事件
        function searchData() {
            // 重新加载数据
            loadBalanceTrendData();
        }
        
        // 重置按钮点击事件
        function resetForm() {
            $("#startTime").val("");
            $("#endTime").val("");
            $("#accountSelect").val("");
            $("#accountSelect").selectpicker('refresh');
            loadBalanceTrendData();
        }
        
        // 导出Excel
        function exportExcel() {
            $.modal.confirm("确定导出所有账户余额数据吗？", function() {
                // 这里可以添加导出Excel的逻辑
                $.modal.alertSuccess("导出成功");
            });
        }
    </script>
</body>
</html> 